extends Node
class_name GameManager

# 游戏管理器 - 单例模式
signal qi_changed(current_qi: int, max_qi: int)
signal realm_changed(realm_name: String)
signal cultivation_speed_changed(speed: int)
signal log_added(message: String)
signal breakthrough_result(success: bool, message: String)

# 子系统
var spirit_root: SpiritRoot
var realm: Realm

# 玩家数据
var player_name: String = "修仙者"
var current_qi: int = 0
var qi_accumulator: float = 0.0  # 灵气累加器，用于精确计算

# 修炼日志(最多保留100条)
var cultivation_logs: Array[String] = []
const MAX_LOGS = 100

# 修炼状态文字
const CULTIVATION_TEXTS = [
	"🌀 灵气缓缓流转...",
	"🌌 感悟天地之道...",
	"💠 丹田灵气充盈...",
	"🌿 气息渐趋平稳...",
	"✨ 天地灵气汇聚...",
	"🌱 修为稳步提升...",
	"🌊 灵力生生不息...",
	"🧘 心神渐入空明...",
	"🌑 周天运转不息...",
	"🌟 道韵缠绕周身..."
]

func _ready():
	# 确保处理模式启用
	set_process(true)
	
	# 初始化子系统
	spirit_root = SpiritRoot.new()
	realm = Realm.new()
	
	# 生成初始灵根
	spirit_root.generate_random_roots()
	add_log("🌟 开始修仙之路...")
	add_log("✨ 觉醒灵根:")
	for root in spirit_root.roots:
		var info = spirit_root.get_root_info(root)
		add_log("  " + info["emoji"] + " " + info["name"] + ": " + info["desc"])
	
	# 发送初始信号
	realm_changed.emit(realm.get_realm_name())
	qi_changed.emit(current_qi, realm.get_max_qi())
	cultivation_speed_changed.emit(get_cultivation_speed())
	
	print("🎮 GameManager 初始化完成")
	print("⚡ 修炼速度: ", get_cultivation_speed(), " 灵气/秒")

func _process(delta):
	# 自动修炼 - 每帧增加灵气
	cultivate(delta)

# 自动修炼
func cultivate(delta: float):
	if realm.current_realm == Realm.RealmLevel.ASCENSION:
		return  # 已飞升,停止修炼
	
	var speed = get_cultivation_speed()
	var qi_gain = speed * delta
	
	# 使用浮点数累加器精确计算
	qi_accumulator += qi_gain
	
	# 当累加器达到 1.0 时，转换为整数灵气
	if qi_accumulator >= 1.0:
		var qi_to_add = int(qi_accumulator)
		current_qi = min(current_qi + qi_to_add, realm.get_max_qi())
		qi_accumulator -= qi_to_add
		qi_changed.emit(current_qi, realm.get_max_qi())

# 计算修炼速度(灵气/秒)
func get_cultivation_speed() -> int:
	var base_speed = realm.get_base_qi_per_sec()
	var qi_bonus = 1.0 + spirit_root.get_total_qi_bonus()
	var speed_bonus = 1.0 + spirit_root.get_total_speed_bonus()
	
	return int(base_speed * qi_bonus * speed_bonus)

# 尝试突破境界
func attempt_breakthrough():
	if current_qi < realm.get_max_qi():
		add_log("⚠️ 灵气不足,无法突破!")
		breakthrough_result.emit(false, "灵气不足,无法突破!")
		return
	
	if not realm.can_breakthrough():
		add_log("🏆 已达巅峰,无法继续突破!")
		breakthrough_result.emit(false, "已达巅峰!")
		return
	
	# 计算成功率
	var base_success_rate = 0.80
	var bonus_success_rate = spirit_root.get_total_success_rate_bonus()
	var total_success_rate = min(base_success_rate + bonus_success_rate, 0.95)  # 最高95%
	
	var roll = randf()
	var old_realm_name = realm.get_realm_name()
	
	if roll < total_success_rate:
		# 突破成功
		realm.breakthrough()
		var new_realm_name = realm.get_realm_name()
		current_qi = 0  # 重置灵气
		qi_accumulator = 0.0  # 重置累加器
		
		add_log("🎉 突破成功! " + old_realm_name + " → " + new_realm_name)
		realm_changed.emit(new_realm_name)
		qi_changed.emit(current_qi, realm.get_max_qi())
		cultivation_speed_changed.emit(get_cultivation_speed())
		breakthrough_result.emit(true, "突破成功!\n" + new_realm_name)
		
		# 检查是否飞升
		if realm.current_realm == Realm.RealmLevel.ASCENSION:
			add_log("🎆 恭喜!你已飞升成仙!")
			breakthrough_result.emit(true, "恭喜飞升成仙!")
	else:
		# 突破失败
		var loss_rate = 0.30
		if spirit_root.has_earth_root():
			loss_rate = 0.20  # 土灵根减少损失
		
		var lost_qi = int(current_qi * loss_rate)
		current_qi -= lost_qi
		
		add_log("💔 突破失败! 损失灵气: " + str(lost_qi))
		qi_changed.emit(current_qi, realm.get_max_qi())
		breakthrough_result.emit(false, "突破失败!\n损失灵气: " + str(lost_qi))

# 洗炼灵根
func refine_spirit_root():
	spirit_root.generate_random_roots()
	add_log("✨ 洗炼灵根成功!")
	add_log("🌟 新的灵根:")
	for root in spirit_root.roots:
		var info = spirit_root.get_root_info(root)
		add_log("  " + info["emoji"] + " " + info["name"] + ": " + info["desc"])
	
	cultivation_speed_changed.emit(get_cultivation_speed())

# 添加日志
func add_log(message: String):
	var timestamp = Time.get_datetime_string_from_system()
	var log_entry = "[" + timestamp + "] " + message
	
	cultivation_logs.insert(0, log_entry)
	if cultivation_logs.size() > MAX_LOGS:
		cultivation_logs.resize(MAX_LOGS)
	
	log_added.emit(log_entry)

# 获取随机修炼状态文字
func get_random_cultivation_text() -> String:
	return CULTIVATION_TEXTS[randi() % CULTIVATION_TEXTS.size()]

# 获取灵气百分比
func get_qi_percentage() -> float:
	var max_qi = realm.get_max_qi()
	if max_qi == 0:
		return 0.0
	return float(current_qi) / float(max_qi)

# 获取所有日志
func get_all_logs() -> Array[String]:
	return cultivation_logs
